<?php

namespace App\Http\Services;

use App\Http\Dao\WechatUserDao;
use App\Http\Services\common\JwtService;
use App\Http\Services\common\WxService;
use App\Models\HotModel;
use App\Models\UserCommentModel;
use App\Models\UserHistoryModel;
use App\Models\UserLikeModel;
use App\Models\WechatUserModel;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use Exception;

/**
 * @property WechatUserDao $wechatUserDao
 */
class AccountService
{

    public function __construct(WechatUserDao $wechatUserDao)
    {
        $this->wechatUserDao = $wechatUserDao;
    }

    /**
     * @throws InvalidConfigException
     * @throws Exception
     */
    public function wxLogin($code)
    {
        $wxService = new WxService();
        $response = $wxService->getUserSession($code);
        if (isset($response['errcode'])) {
            throw new Exception($response['errmsg']);
        }

        $wxUserInfo = $this->wechatUserDao->getOne(['openid' => $response['openid']]);
        if (empty($wxUserInfo)) {
            // 新增用户
            $wxUserInfo = WechatUserModel::query()->create([
                'openid' => $response['openid'],
                'session_key' => $response['session_key']
            ]);
        } else {
            $wxUserInfo->session_key = $response['session_key'];
            $wxUserInfo->save();
        }
        $wxUserInfo = $wxUserInfo->toArray();
        $wxUserInfo['token'] = JwtService::createToken($wxUserInfo['id']);
        return $wxUserInfo;
    }

    public function setUserInfo($post)
    {
        $wxUserInfo = $this->wechatUserDao->getOne(['openid' => request()->userInfo['openid']]);
        if (empty($wxUserInfo)) {
            return false;
        }
        if (!empty($post['nickname'])) {
            $wxUserInfo->nickname = $post['nickname'];
        }
        if (!empty($post['avatarUrl'])) {
            $wxUserInfo->headimgurl = $post['avatarUrl'];
        }
        return $wxUserInfo->save();
    }

    /**
     * 刷新用户token
     * @param string $openId 微信openId
     * @return array
     * @throws Exception
     */
    public function refreshToken($openId)
    {
        // 输入验证
        if (empty($openId)) {
            throw new Exception('OpenID不能为空');
        }
        
        // 获取用户信息并检查是否存在
        $userInfo = $this->wechatUserDao->getUserInfo($openId);
        if (empty($userInfo)) {
            throw new Exception('用户不存在');
        }
        
        // 生成新token
        $token = JwtService::createToken($userInfo->id);
        return ['token' => $token];
    }

    public function getUserInfo()
    {
        $userInfo = $this->wechatUserDao->getOne(['id' => request()->userInfo['id']]);
        return $userInfo ? $userInfo->toArray() : [];
    }

    public function clearHistory($userId)
    {
        return $this->wechatUserDao->clearHistory($userId);
    }

    public function getHistoryList($openId)
    {
        $userInfo = $this->wechatUserDao->getUserInfo($openId);
        $userHistory = UserHistoryModel::query()->selectRaw('distinct keyword')->where('user_id', $userInfo->id)->get()->toArray();
        $hot = HotModel::query()->orderBy('sort', 'desc')->limit(10)->get()->toArray();

        return ['hot' => $hot, 'history' => $userHistory];
    }

    public function saveHistory($postArr)
    {
        return UserHistoryModel::query()->create([
            'user_id' => request()->userInfo['id'],
            'keyword' => $postArr['search_value']
        ]);
    }

    public function addComment($postArr)
    {
        return UserCommentModel::query()->create([
            'user_id' => request()->userInfo['id'],
            'q_id' => $postArr['question_id'],
            'content' => $postArr['content']
        ]);
    }

    public function getCommentList($qId)
    {
        return UserCommentModel::query()->with(['users'])->where('q_id', $qId)->where('status', 1)
            ->orderBy('hot_level', 'desc')
            ->orderBy('created_at', 'desc')
            ->get()->toArray();
    }

    public function toggleLike($qId)
    {
        $info = UserLikeModel::query()
            ->where('q_id', $qId)
            ->where('user_id', request()->userInfo['id'])
            ->where('type', 1)
            ->first();
        if ($info) {
            return UserLikeModel::query()->where('id', $info['id'])->delete();
        } else {
            return UserLikeModel::query()->create([
                'q_id' => $qId,
                'user_id' => request()->userInfo['id'],
                'type' => 1
            ]);
        }
    }

    public function getLikeInfo($qId)
    {
        $info = UserLikeModel::query()
            ->where('q_id', $qId)
            ->where('user_id', request()->userInfo['id'])
            ->where('type', 1)
            ->first();

        return $info ? $info->toArray() : [];
    }

    /**
     * 添加收藏
     * @param int $qId 题目ID
     * @return bool
     */
    public function addFavorite($qId)
    {
        // 检查是否已收藏
        $existing = UserLikeModel::query()
            ->where('q_id', $qId)
            ->where('user_id', request()->userInfo['id'])
            ->where('type', 2)
            ->first();

        if ($existing) {
            return false; // 已收藏
        }

        return UserLikeModel::query()->create([
            'q_id' => $qId,
            'user_id' => request()->userInfo['id'],
            'type' => 2
        ]);
    }

    /**
     * 取消收藏
     * @param int $qId 题目ID
     * @return bool
     */
    public function removeFavorite($qId)
    {
        return UserLikeModel::query()
            ->where('q_id', $qId)
            ->where('user_id', request()->userInfo['id'])
            ->where('type', 2)
            ->delete();
    }

    /**
     * 获取收藏列表
     * @return array
     */
    public function getFavoriteList()
    {
        return UserLikeModel::query()
            ->with(['question' => function($query) {
                $query->select('id', 'question_text', 'answer', 's_id', 't_id', 'difficulty', 'created_at');
            }])
            ->where('user_id', request()->userInfo['id'])
            ->where('type', 2)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();
    }

    /**
     * 检查是否已收藏
     * @param int $qId 题目ID
     * @return array
     */
    public function checkFavorite($qId)
    {
        $info = UserLikeModel::query()
            ->where('q_id', $qId)
            ->where('user_id', request()->userInfo['id'])
            ->where('type', 2)
            ->first();

        return [
            'is_favorite' => !empty($info),
            'favorite_info' => $info ? $info->toArray() : []
        ];
    }
}
